import type { SearchSelectorConfig } from '../../../../module/page_enhancer/appearance/style_enhancement/platforms'
import type { BingPageTypeResult } from './types'
import { PageRoute } from '../../../abstract/page_route'
import { BING_SEARCH_PAGE_SELECTORS, BingPageType } from './types'

export class BingPage extends PageRoute {
  readonly name: string = 'BingPage'
  private static instance: BingPage
  get pageType(): BingPageType | 'default' {
    return this.getCurrentPageMeta().type
  }

  /**
   * 获取单例实例
   */
  public static getInstance(): BingPage {
    if (!BingPage.instance) {
      BingPage.instance = new BingPage()
    }
    return BingPage.instance
  }

  /**
   * 获取结果选择器
   */
  getResultSelectors(pageType?: BingPageType, includeHideElement: boolean = true): SearchSelectorConfig {
    return this.resultSelectors(
      {
        pageType: pageType || this.pageType,
        selectorConfig: BING_SEARCH_PAGE_SELECTORS,
        includeHideElement,
        supportedPages: [
          BingPageType.Web,
          BingPageType.Video,
          BingPageType.Academic,
          BingPageType.Dictionary,
        ],
      },
    )
  }

  /**
   * 获取当前页面类型
   */
  public getCurrentPageMeta(): BingPageTypeResult {
    const url = this.getCurrentUrl()
    const path = new URL(url).pathname

    // 404 页面检测
    const notFoundResult = this.detectNotFoundPage()
    if (notFoundResult)
      return notFoundResult

    // 首页
    if (/^\/?$/.test(path)) {
      return { type: BingPageType.Index }
    }

    // 基础页面检测
    const pageResult = this.detectPages(path)
    if (pageResult)
      return pageResult

    // 未定义页面
    return { type: BingPageType.Undefined }
  }

  /**
   * 检测 404 页面
   */
  private detectNotFoundPage(): BingPageTypeResult | null {
    const pageNotFoundRules = [
      /404.*Not Found/i, // 不区分大小写
    ]

    if (pageNotFoundRules.some(regex => regex.test(document.title))) {
      return { type: BingPageType.NotFound }
    }

    return null
  }

  /**
   * 检测其他功能页面
   */
  private detectPages(basePath: string): BingPageTypeResult | null {
    const pageDetectors: Array<[RegExp, (...args: any[]) => BingPageTypeResult]> = [
      // 网页
      [/^\/search\/?$/, () => {
        return { type: BingPageType.Web }
      }],
      // 图片
      // 视频
      [/^\/videos\/search\/?$/, () => {
        return { type: BingPageType.Video }
      }],
      // 学术
      [/^\/academic\/search\/?$/, () => {
        return { type: BingPageType.Academic }
      }],
      // 词典
      [/^\/dict\/search\/?$/, () => {
        return { type: BingPageType.Dictionary }
      }],
    ]

    for (const [regex, handler] of pageDetectors) {
      const match = basePath.match(regex)
      if (match) {
        return handler(match)
      }
    }

    return null
  }
}
